package com.naihe.anderson.sms.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;

public class ImageUtil {
    public static final String WEIBOCALL_PROFILE_IMAGE_LOCATION = "/sdcard/qingzhi-net/weibocall/profile_img/";


    /**
     * 图片压缩
     * @param photoData
     * @param sizeParamFloat
     * @return
     */
    public static Bitmap compressPhoto(byte[] photoData, float sizeParamFloat) {
		if (photoData.length == 0) {
			return null;
		}
		Bitmap photoBitmap;
		BitmapFactory.Options options = new BitmapFactory.Options();   
		options.inJustDecodeBounds = true;  //如果inJustDecodeBounds值为true，则decodeByteArray不会生成图片，只是去计算图片的信息
		BitmapFactory.decodeByteArray(photoData, 0, photoData.length, options); 
		
		int wht = 0;
		if (options.outWidth > options.outHeight){
			wht = options.outWidth;
		}else{
			wht = options.outHeight;
		}
		
		options.inJustDecodeBounds = false;
		int inSS = (int) (wht / sizeParamFloat);
		if (inSS <= 0) {
			inSS = 1;
		}
		options.inSampleSize = inSS;
		photoBitmap = BitmapFactory.decodeByteArray(photoData, 0, photoData.length, options);
		
		return photoBitmap;
	}


	public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidht = ((float) w / width);
		float scaleHeight = ((float) h / height);
		matrix.postScale(scaleWidht, scaleHeight);
		Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		return newbmp;
	}

	/**
	 * 图片资源文件转换成Bitmap
	 * @param drawable
	 * @return
	 */
	public static Bitmap drawableToBitmap(Drawable drawable) {
		int width = drawable.getIntrinsicWidth();
		int height = drawable.getIntrinsicHeight();
		Bitmap bitmap = Bitmap.createBitmap(width, height, drawable
				.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
				: Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, width, height);
		drawable.draw(canvas);
		return bitmap;

	}

	/**
	 * 创建圆角图片
	 * @param inputBitmap
	 * @param radiusSize
	 * @return
	 */
	public static Bitmap createRoundedCornerBitmap(Bitmap inputBitmap, float radiusSize) {
		
		Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap.getWidth(), inputBitmap.getHeight(), Bitmap.Config.ARGB_8888);

		Canvas localCanvas = new Canvas(outputBitmap);

		Rect rect = new Rect(0, 0, inputBitmap.getWidth(), inputBitmap.getHeight());
		RectF rectF = new RectF(rect);

		final int colorFg = 0xff424242;
		
		Paint paint = new Paint();
		paint.setAntiAlias(true);
		paint.setDither(true);
		paint.setFilterBitmap(true);
		localCanvas.drawARGB(0, 0, 0, 0);
		paint.setColor(colorFg);
		
		

		localCanvas.drawRoundRect(rectF, radiusSize, radiusSize, paint);
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		localCanvas.drawBitmap(inputBitmap, rect, rect, paint);

//		if (!inputBitmap.isRecycled()) {
//			inputBitmap.recycle();
//		}
		
		return outputBitmap;
	}

	public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
		final int reflectionGap = 4;
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();

		Matrix matrix = new Matrix();
		matrix.preScale(1, -1);

		Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2,
				width, height / 2, matrix, false);

		Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
				(height + height / 2), Config.ARGB_8888);

		Canvas canvas = new Canvas(bitmapWithReflection);
		canvas.drawBitmap(bitmap, 0, 0, null);
		Paint deafalutPaint = new Paint();
		canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);

		canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

		Paint paint = new Paint();
		LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
				bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,
				0x00ffffff, TileMode.CLAMP);
		paint.setShader(shader);
		// Set the Transfer mode to be porter duff and destination in
		paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
		// Draw a rectangle using the paint with our linear gradient
		canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
				+ reflectionGap, paint);

		return bitmapWithReflection;
	}

    public static String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyy-MM-dd HH.mm.ss");
        return dateFormat.format(date) + ".jpg";
    }

    /**
     * 把原先保存png文件的方法重写了一份，增加保存类型参数，同样一个图片保存为PNG格式会比JPEG格式占用空间大很多
     *
     * @param format JPEG或者PNG
     */
    public static void bitmapSava(Bitmap bitmap, String filename, Bitmap.CompressFormat format) {

        if (bitmap == null || TextUtils.isEmpty(filename)) {
            return;
        }
        String path = filename.substring(0, filename.lastIndexOf("/"));
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File file = new File(filename);
        if(file.exists()){
        	return;
        }
        
        FileOutputStream fOut = null;
        try {
            file.createNewFile();
            fOut = new FileOutputStream(file);
            bitmap.compress(format, 100, fOut);
            fOut.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fOut != null)
                    fOut.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * ���ֳ������СBitmap
     *
     * @param bitmap
     * @param maxWidth
     * @param maxHeight
     * @return
     */
    public static Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {

        int originWidth = bitmap.getWidth();
        int originHeight = bitmap.getHeight();

        // no need to resize
        if (originWidth < maxWidth && originHeight < maxHeight) {
            return bitmap;
        }

        int width = originWidth;
        int height = originHeight;

        if (originWidth > maxWidth) {
            width = maxWidth;

            double i = originWidth * 1.0 / maxWidth;
            height = (int) Math.floor(originHeight / i);

            bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
        }

        if (height > maxHeight) {
            height = maxHeight;
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
        }

//        Log.i(TAG, width + " width");
//        Log.i(TAG, height + " height");

        return bitmap;
    }
}
